package top.codecrab.eblog.utils;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.net.Ipv4Util;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Random;

/**
 * @author codecrab
 */
@Slf4j
public class CommonUtils {

    /**
     * 获取客户端真实IP
     */
    public static String getRemoteHost(HttpServletRequest request) {
        String clientIP = ServletUtil.getClientIP(request);
        if ("0:0:0:0:0:0:0:1".equals(clientIP)) {
            clientIP = "127.0.0.1";
        }
        return clientIP;
    }

    /**
     * 获取一言的sign
     */
    public static String getSign() {
        String url = "https://v1.hitokoto.cn?encode=json&charset=utf-8&c=a&c=b&c=d&c=e&c=f&c=g&c=h&c=i&c=j&c=k&c=l&c=c";
        try {
            HttpResponse response = HttpRequest.get(url).execute();
            if (response.getStatus() == HttpStatus.HTTP_OK) {
                return MapUtil.getStr(JSONUtil.toBean(response.body(), Map.class), "hitokoto");
            }
            return "这个人很懒，什么都没有写。";
        } catch (HttpException e) {
            log.error("获取一言的sign失败！", e);
            return "这个人很懒，什么都没有写。";
        }
    }

    /**
     * 生成随机用户名，中文组成
     *
     * @param length 生成字符串的长度
     */
    public static String getRandomChineseStr(int length) {
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < length; i++) {
            String str = null;
            int heightPos, lowPos; // 定义高低位
            Random random = new Random();
            // 获取高位值
            heightPos = (176 + Math.abs(random.nextInt(39)));
            // 获取低位值
            lowPos = (161 + Math.abs(random.nextInt(93)));
            byte[] b = new byte[2];
            b[0] = (new Integer(heightPos).byteValue());
            b[1] = (new Integer(lowPos).byteValue());
            try {
                // 转成中文
                str = new String(b, "GBK");
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
            ret.append(str);
        }
        return ret.toString();
    }

}
